<template>
  <div>
    <!-- 地图容器 -->
    <div id="gdpContainer"></div>

    <!-- 查询面板 -->
    <el-card id="extend" v-show="!isHidden" @click="hidden">+</el-card>
    <el-card id="GDPsearchPanel" v-show="isHidden">
      <div id="hiddenButton" @click="hidden">-</div>
      <!-- 选择查询城市 -->
      <el-select
        v-model="searchProvince"
        placeholder="省份"
        size="large"
        @change="provinceChanged"
      >
        <el-option
          v-for="item in cityOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <!-- 选择年份 -->
      <!-- <el-select
        v-model="years"
        placeholder="年份"
        size="large"
        @change="yearsChanged"
        v-show="activeName == 'pieChart'"
      >
        <el-option
          v-for="item in yearOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select> -->

      <!-- 标签切换视图 -->
      <el-tabs v-model="activeName">
        <!-- 数据表格 -->
        <el-tab-pane label="表格" name="table">
          <el-table
            :data="GDPdata.data"
            height="250"
            style="width: 100%"
            :default-sort="{ prop: 'year', order: 'descending' }"
          >
            <el-table-column prop="year" label="年份" width="190" sortable />
            <el-table-column
              prop="gdp"
              label="国民生产总值(亿元)"
              width="190"
              sortable
            />
            <el-table-column
              prop="gdp_coverage"
              label="人均国民生产总值(元)"
              width="190"
              sortable
            />
            <el-table-column
              prop="first_industry"
              label="第一产业增加值(亿元)"
              width="190"
              sortable
            />
            <el-table-column
              prop="second_industry"
              label="第二产业增加值(亿元)"
              width="190"
              sortable
            />
            <el-table-column
              prop="third_industry"
              label="第三产业增加值(亿元)"
              width="190"
              sortable
            />
          </el-table>
        </el-tab-pane>

        <!-- 折线图 -->
        <el-tab-pane label="走势" name="lineChart">
          <div id="lineChartContainer"></div>
        </el-tab-pane>

        <!-- 饼图 -->
        <el-tab-pane label="成分组成" name="pieChart">
          <div id="pieChartContainer"></div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onActivated,
  onDeactivated,
  watch,
  onMounted,
  nextTick,
  h,
} from "vue";
import { shallowRef } from "@vue/reactivity";
import { createRegion } from "@/tools/createRegion.js";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import AMapLoader from "@amap/amap-jsapi-loader";
import { cityOption } from "@/tools/cityOptions.js";
import axios from "axios";
import { getGDPdataReq } from "@/networks/getGDPdata.js";

window._AMapSecurityConfig = {
  //高德地图API安全码
  securityJsCode: "7a147469fc71afc2c2540196e2453b2b",
};

let map = shallowRef(null); //地图容器
let searchProvince = ref(null);
let activeName = ref("table"); //标签切换绑定值
let GDPdata = reactive({ data: [] });
// let years = ref(null);
// let yearOption = [];
// for (let i = 2021; i >= 2012; i--) {
//   yearOption.push({ value: i + "", label: `${i}年` });
// }

//加载地图的函数
const initMap = function () {
  if (map.value != null) {
    map.value.destroy();
    // map.value.clearMap();
  }
  AMapLoader.load({
    key: "2b45c6a7655404e69a9b856504d8625c", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  }).then((AMap) => {
    map.value = new AMap.Map("gdpContainer", {
      viewMode: "3D", //是否为3D地图模式
      zoom: 10, //初始化地图级别
      center: [117.301291, 31.844148], //初始化地图中心点位置
      // mapStyle: "amap://styles/45311ae996a8bea0da10ad5151f72979",
      mapStyle: "amap://styles/dark",
      showIndoorMap: true,
    });
    // 加载插件
    AMap.plugin(
      [
        "AMap.ToolBar",
        "AMap.Geolocation",
        "AMap.DistrictSearch",
        "AMap.InfoWindow",
      ],
      async function () {
        map.value.addControl(new AMap.Geolocation());
        // 绘制行政区
        if (searchProvince.value != null) {
          let district = new AMap.DistrictSearch({
            // 返回行政区边界坐标等具体信息
            extensions: "all",
            // 设置查询行政区级别为 区
            level: "district",
          });
          await district.search(
            searchProvince.value,
            function (status, result) {
              // 获取合肥市的边界信息
              let bounds = result.districtList[0].boundaries;
              let polygons = [];
              if (bounds) {
                for (let i = 0, l = bounds.length; i < l; i++) {
                  //生成行政区划polygon
                  let polygon = new AMap.Polygon({
                    map: map.value,
                    strokeWeight: 1,
                    path: bounds[i],
                    fillOpacity: 0.7,
                    fillColor: "#909399",
                    strokeColor: "#CC66CC",
                  });
                  polygons.push(polygon);
                }
                // 地图自适应
                map.value.setFitView();
              }
            }
          );
        }
      }
    );

    // 操作地图
  });
};

// 获取gdp数据
const getData = async function () {
  if (searchProvince.value == null) {
    return;
  }
  try {
    const { data: res } = await getGDPdataReq({ city: searchProvince.value });
    if (res.status != 200) {
      return ElMessage.error("获取数据失败，请重试");
    }
    GDPdata.data = res.data;
    // console.log(GDPdata.data);
    ElMessage.success("数据获取成功");
  } catch (err) {
    console.log(err);
  }
};

// 创建GDP走势图表
function createLineChart() {
  let lineChartContainer = document.querySelector("#lineChartContainer");
  if (lineChartContainer == null || GDPdata.data.length == 0) return;
  echarts.dispose(lineChartContainer);
  let lineChart = echarts.init(lineChartContainer);
  let gdp = [],
    first_industry = [],
    second_industry = [],
    third_industry = [];
  for (let i = 0; i < GDPdata.data.length; i++) {
    gdp.push(GDPdata.data[i].gdp);
    first_industry.push(GDPdata.data[i].first_industry);
    second_industry.push(GDPdata.data[i].second_industry);
    third_industry.push(GDPdata.data[i].third_industry);
  }
  // 图表配置项
  lineChart.setOption({
    title: {
      text: `2012-2021${searchProvince.value}GDP`,
    },
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        dataView: { readOnly: false },
        magicType: { type: ["line", "bar"] },
        restore: {},
        saveAsImage: {},
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      top: "100px",
    },
    legend: {
      left: "100px",
      top: "30px",
    },
    xAxis: {
      name: "年份",
      data: [2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021],
      type: "category",
      boundaryGap: false,
    },
    yAxis: {
      name: "亿元",
      type: "value",
      offset: "20",
    },
    series: [
      {
        name: "国民生产总值",
        type: "line",
        data: gdp,
      },
      {
        name: "第一产业增加值",
        type: "line",
        data: first_industry,
      },
      {
        name: "第二产业增加值",
        type: "line",
        data: second_industry,
      },
      {
        name: "第三产业增加值",
        type: "line",
        data: third_industry,
      },
    ],
  });
}

//创建GDP占比图
function createPieChart() {
  let pieChartContainer = document.querySelector("#pieChartContainer");
  if (pieChartContainer == null || GDPdata.data.length == 0) return;
  echarts.dispose(pieChartContainer);
  let pieChart = echarts.init(pieChartContainer);
  let source = [
    [
      "产业",
      "2012",
      "2013",
      "2014",
      "2015",
      "2016",
      "2017",
      "2018",
      "2019",
      "2020",
      "2021",
    ],
    ["第一产业"],
    ["第二产业"],
    ["第三产业"],
  ];
  GDPdata.data.map((item) => {
    source[1].push(item.first_industry);
    source[2].push(item.second_industry);
    source[3].push(item.third_industry);
  });
  // console.log(source)

  pieChart.setOption({
    title: {
      text: `${searchProvince.value}GDP组成`,
    },
    legend: {},
    tooltip: {
      trigger: "axis",
      showContent: false,
    },
    dataset: {
      source,
    },
    toolbox: {
      show: true,
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        dataView: { readOnly: false },
        magicType: { type: ["line", "bar"] },
        restore: {},
        saveAsImage: {},
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    xAxis: { type: "category" },
    yAxis: { gridIndex: 0 },
    grid: { top: "55%" },
    series: [
      {
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        emphasis: { focus: "series" },
      },
      {
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        emphasis: { focus: "series" },
      },
      {
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        emphasis: { focus: "series" },
      },
      {
        type: "pie",
        id: "pie",
        radius: "30%",
        center: ["50%", "25%"],
        emphasis: {
          focus: "self",
        },
        label: {
          formatter: " {@2012} ({d}%)",
        },
        encode: {
          itemName: "product",
          value: "2012",
          tooltip: "2012",
        },
      },
    ],
  });

  pieChart.on("updateAxisPointer", function (event) {
    const xAxisInfo = event.axesInfo[0];
    if (xAxisInfo) {
      const dimension = xAxisInfo.value + 1;
      pieChart.setOption({
        series: {
          id: "pie",
          label: {
            formatter: " {@[" + dimension + "]} ({d}%)",
          },
          encode: {
            value: dimension,
            tooltip: dimension,
          },
        },
      });
    }
  });
}

let isHidden = ref(true);
function hidden() {
  isHidden.value = !isHidden.value;
}

onActivated(() => {
  nextTick(() => {
    initMap();
  });
});

onDeactivated(() => {
  map.value?.destroy();
  map.value?.clearMap();
});

// 监听选择器变化
async function provinceChanged(value) {
  // console.log(e)
  await getData();
  if (activeName.value == "lineChart") {
    createLineChart();
  } else if (activeName.value == "pieChart") {
    createPieChart();
  }
  initMap();
}

// 监听年份变化
// async function yearsChanged() {

// }

watch(activeName, () => {
  nextTick(() => {
    if (activeName.value == "lineChart") {
      createLineChart();
    } else if (activeName.value == "pieChart") {
      createPieChart();
    }
  });
});
</script>

<script>
export default {
  name: "gdp",
  data() {
    return {};
  },
  methods: {},
};
</script>

<style lang="less" scoped>
#gdpContainer {
  width: calc(100vw - 200px);
  height: calc(100vh - 3rem);
  position: absolute;
  top: 3rem;
  left: 200px;
}

#GDPsearchPanel {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
}

#lineChartContainer {
  width: 50vw;
  height: 50vh;
  margin: 20px 50px;
}

#pieChartContainer {
  width: 40vw;
  height: 65vh;
  margin: 20px 50px;
}

#hiddenButton {
  position: absolute;
  right: 20px;
  font-size: 3rem;
  top: -10px;
  cursor: pointer;
}

#extend {
  position: absolute;
  z-index: 2;
  top: 5rem;
  left: calc(1.5rem + 200px);
  font-size: 2rem;
  cursor: pointer;
}
</style>
